<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="4">
          <el-button type="primary" @click="addRolesDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>

      <el-table :data="rolesList" style="width: 100%" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 一级权限 -->
            <el-row v-for="(item,index) in scope.row.children" :key="item.id"
              :class="['rightBottom', index === 0 ? 'rightTop' : '','vcenter']">
              <el-col :span="5">
                <el-tag closable @close="deleteRightsById(scope.row, item)">{{item.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <!-- 二级权限 -->
                <el-row v-for="(item2, index2) in item.children" :key="item2.id"
                  :class="[index2 === 0 ? '': 'rightTop','vcenter']">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="deleteRightsById(scope.row, item2)">{{item2.authName}}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <!-- 三级权限 -->
                    <el-tag type="warning" v-for="(item3) in item2.children" :key="item3.id" closable
                      @close="deleteRightsById(scope.row, item3)">{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditRoleDialog(scope.row.id)">编辑
            </el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteRole(scope.row.id)">删除</el-button>
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightsDialog(scope.row)">权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色对话框 -->

    <el-dialog title="添加角色" :visible.sync="addRolesDialogVisible" width="30%" @close="addRolesDialogClose">
      <!-- 对话框表单 -->
      <el-form :model="addRolesForm" :rules="addRolesFormRules" ref="addRolesFormRef" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="addRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改角色 -->
    <el-dialog title="修改角色信息" :visible.sync="editRolesDialogVisible" width="50%" @close="editRolesDialogClose">
      <el-form :model="editRolesForm" ref="editRolesFormRef" label-width="80px">
        <el-form-item label="角色名称">
          <el-input v-model="editRolesForm.roleName" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog title="分配权限" :visible.sync="setRightsDialogVisible" width="40%" @close="setRightsDialogClose">
      <el-tree :data="setRightsList" :props="rightsProps" show-checkbox default-expand-all node-key="id"
        :default-checked-keys="rightsCheckedKeys" ref="setRightsRef"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rolesList: [],

      addRolesForm: {
        roleName: '',
        roleDesc: '',
      },

      editRolesForm: {},

      //展示权限数据
      setRightsList: [],
      rightsProps: {
        label: 'authName',
        children: 'children',
      },
      rightsCheckedKeys: [],
      //授权的角色id
      setRightsRoleId: '',


      addRolesDialogVisible: false,
      editRolesDialogVisible: false,
      setRightsDialogVisible: false,

      //校验规则
      addRolesFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
        ],
      },
    }
  },

  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('请求服务器失败，无法获取角色数据')
      }
      this.rolesList = res.data
    },
    //添加角色
    async addRoles() {
      const { data: res } = await this.$http.post('roles', this.addRolesForm)
      if (res.meta.status !== 201) {
        return this.$message.error('请求服务器失败，无法添加角色信息')
      }
      this.$message.success('添加角色成功')
      this.addRolesDialogVisible = false
      this.getRolesList()
    },
    //修改角色对话框
    async showEditRoleDialog(roleId) {
      this.editRolesDialogVisible = true
      const { data: res } = await this.$http.get(`roles/${roleId}`)
      if (res.meta.status !== 200) {
        return this.$message.error('请求服务器失败，无法修改当前角色信息')
      }
      this.editRolesForm = res.data
    },
    //修改角色信息
    async editRole() {
      const { data: res } = await this.$http.put(
        `roles/${this.editRolesForm.roleId}`,
        {
          roleName: this.editRolesForm.roleName,
          roleDesc: this.editRolesForm.roleDesc,
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('请求服务器失败，无法修改当前角色信息')
      }
      this.$message.success('修改角色信息成功')
      this.editRolesDialogVisible = false
      this.getRolesList()
    },
    //删除角色信息
    async deleteRole(roleId) {
      const confirmRes = await this.$confirm(
        '此操作将永久删除此角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((error) => error)
      if (confirmRes !== 'confirm') {
        return this.$message.info('取消删除')
      }
      const { data: res } = await this.$http.delete(`roles/${roleId}`)
      if (res.meta.status !== 200) {
        return this.$message.error('请求服务器失败，无法删除此角色')
      }
      this.$message.success('删除成功')
      this.getRolesList()
    },
    //删除角色下的权限
    async deleteRightsById(role, rightId) {
      const confirmRes = await this.$confirm(
        '此操作将永久删除此权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((error) => error)
      if (confirmRes !== 'confirm') {
        return this.$message.info('取消删除')
      }
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('请求服务器失败，无法删除此权限')
      }
      roles.children = res.data
    },
    //权限分配对话框
    async showSetRightsDialog(roles) {
      this.setRightsDialogVisible = true
      //获取树形结构所有权限
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限数据失败')
      }
      this.setRightsList = res.data
      this.setRightsRoleId = roles.id
      this.getLeafRightsKey(roles,this.rightsCheckedKeys)
    },
    //递归获取三级权限id
    getLeafRightsKey(roleNode,arrKeys){
      if(!roleNode.children){
       return arrKeys.push(roleNode.id)
      }
      roleNode.children.forEach(element => {
        return this.getLeafRightsKey(element, arrKeys)
      });
    },

    //角色授权
    async setRights(){
      //获取所有授权的节点的key
      const keys = [
        ...this.$refs.setRightsRef.getCheckedKeys(),
        ...this.$refs.setRightsRef.getHalfCheckedKeys()
      ]
      const rids = keys.join(',')
      const {data: res} = await this.$http.post(`roles/${this.setRightsRoleId}/rights`, {rids: rids})
      if(res.meta.status !== 200){
        return this.$message.error("请求服务器失败，无法授予权限")
      }
      this.$message.success("权限设置成功")
      this.setRightsDialogVisible = false
      this.getRolesList()
    },

    //重置表单
    addRolesDialogClose() {
      this.$refs.addRolesFormRef.resetFields()
    },
    editRolesDialogClose() {
      this.$refs.editRolesFormRef.resetFields()
    },
    setRightsDialogClose(){
      this.rightsCheckedKeys = []
    },
  },

  created() {
    this.getRolesList()
  },
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 10px;
  margin-left: 20px;
}
.rightTop {
  border-top: 1px solid #eee;
}
.rightBottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
.el-tree {
  margin-left: 50px;
}
</style>
